/** @addtogroup TCP
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include "../../exatron/inc/common.h"

Socket_t sock;

int main(int argc, char *argv[])
{
    socklen_t clilen;
    int n=0;
    int yes=1;

    if(argc < 2)
    {
        printf("\nUso: st_server Porta\r\n\n");
        return 1;
    }

    bzero((char *)&sock.seraddr,sizeof(sock.seraddr));

    /* Abre o socket */
    sock.serfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock.serfd < 0)
    {
        exit(1);
    }

    sock.seraddr.sin_port = htons(atoi(argv[1]));
    sock.seraddr.sin_family = AF_INET;
    sock.seraddr.sin_addr.s_addr = INADDR_ANY;        // Pŕoprio IP

    /* Reutiliza a porta */
    if(setsockopt(sock.serfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1)
    {
        printf("Error on setsockopt\n\r");
        exit(1);
    }

    if(bind(sock.serfd,(struct sockaddr *)&sock.seraddr,sizeof(sock.seraddr))<0)
    {
        printf("Error on binding\n\r");
        exit(1);
    }

    /* Houve uma conexão */
    if(listen(sock.serfd,1)<0)
    {
        printf("Error on listen\n\r");
        exit(1);
    }

    clilen = sizeof(sock.cliaddr);

    while(1)
    {
    	printf("\r\nEsperando por conexao...\r\n");
        sock.clifd = accept(sock.serfd,(struct sockaddr *)&sock.cliaddr,&clilen);
        if(sock.clifd < 0)
        	printf("Error on accept\n\r");

        printf("\r\nConectou com %s\r\n", inet_ntoa(sock.cliaddr.sin_addr));

        do
        {
                bzero(sock.Data.buf_rx,RX_BUF_LEN);
                do
                {
                    n = read(sock.clifd,sock.Data.buf_rx,RX_BUF_LEN);
                }while(n==-1);

                if(n != -1 && n != 0)
                	printf("Recebi: %s\r\n",sock.Data.buf_rx);

                write(sock.clifd,sock.Data.buf_rx,strlen(sock.Data.buf_rx));
                tcdrain(sock.clifd);
        }while(n != 0);

        printf("Desconectou!\n\r");
        close(sock.clifd);
    }
    close(sock.clifd);

    return 0;
}
